<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { ElTable, ElMessage, ElMessageBox } from 'element-plus'
import { vendorPageService } from '@/api/basic/vendor'
import { storePageService } from '@/api/basic/store'
import { purchasePageService, purchaseAddService,purchaseDeleteService } from '@/api/purchase/purchase'
import { materialNameService } from '@/api/material/material'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'

// 采购单接口
interface Purchase {
  id: number
  barcode: string //条码
  store: string //仓库
  vendor: string //供应商
  materialName: String //商品名称
  materialBarcode: String //商品条码
  totalAmount: number //采购金额
  quantity: number //采购数量
  createTime: string //操作日期
  operator: string //操作人
}

// 采购单接口
interface Form {
  id: number
  store: string //仓库
  vendor: string //供应商
  material: number //商品名称
  quantity: number //采购数量
}

// 数据表格
const tableData = ref<Purchase[]>([])
// 商品表单
const form = ref<Form>({});
// 搜索框
const barcodeSearch = ref('')
// 仓库选择器
const storeSelect = ref('')
const storeOptions = ref([]);
// 供应商选择器
const vendorSelect = ref('')
const vendorOptions = ref([]);
// 商品选择器
const MaterialNameSelect = ref('')
const MaterialNameOptions = ref([]);
// 抽屉是否显示
const addDrawer = ref(false);
//分页数据模型
const pageNum = ref(1)//当前页
const pageSize = ref(10)//每页条数
const total = ref(20)//总条数

// 分页数据监听
watch([() => pageNum.value, () => pageSize.value], async () => {
  await getPurchase();
});

// 监听供应商选择器变化，如变化则刷新可选商品列表
watch(() => form.value.vendor, async (newVendor) => {
  if (newVendor) {
      form.value.material = ''
      MaterialNameOptions.value = []
      const result = await materialNameService({ vendorId: newVendor });
      MaterialNameOptions.value = result.map(item => ({
        label: item.name,
        value: item.id,
      }));
  } else {
    MaterialNameOptions.value = []; // 如果供应商清空，重置商品名称选项
  }
});

// 商品列表查询
const getPurchase = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    barcode: barcodeSearch.value ? barcodeSearch.value : null,
    storeId: storeSelect.value ? storeSelect.value : null,
    vendorId: vendorSelect.value ? vendorSelect.value : null
  }
  let result = await purchasePageService(params)
  tableData.value = result.records
  total.value = result.total
}

// 挂载函数，渲染列表
onMounted(async () => {
  await getPurchase();
  let store = await storePageService()
  let vendor = await vendorPageService()
  // 遍历返回的仓库对象
  storeOptions.value = store.map(item => ({
    label: item.name,
    value: item.id,
  }));
  vendorOptions.value = vendor.map(item => ({
    label: item.name,
    value: item.id,
  }));
})

// 添加表单校验规则
const rules = ref({
  vendor: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  store: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  material: [
    { required: true, message: '请选择商品', trigger: 'change' },
  ],
  quantity: [
    { required: true, message: '请输入销售数量', trigger: 'blur' },
    { type: 'number', message: '销售数量必须为数字', trigger: 'blur', transform: (value) => Number(value) },
    { type: 'number', min: 1, message: '销售数量必须大于0', trigger: 'blur', transform: (value) => Number(value) },
    {
      validator: (rule, value, callback) => {
        if (value && !Number.isInteger(Number(value))) {
          callback(new Error('销售数量必须为整数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 修改添加方法，添加表单校验
const formRef = ref(null)
const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      let params = form.value
      purchaseAddService(params).then(() => {
        ElMessage.success("添加成功")
        addDrawer.value = false
        getPurchase()
      })
    }
  })
}

// 取消添加
const addCancel = () => {
  addDrawer.value = false
  form.value = {}
}

// 查找
const search = () => {
  getPurchase().then(() => {
    ElMessage.success("查询成功")
  })
}

// 重置
const reset = () => {
  barcodeSearch.value = ''
  storeSelect.value = ''
  vendorSelect.value = ''
}

// 刷新
const refresh = () => {
  reset()
  getPurchase()
  ElMessage.success("刷新成功")
}

// 添加导出Excel功能
const exportToExcel = () => {
  // 准备导出数据
  const exportData = tableData.value.map(item => ({
    '单据号': item.barcode,
    '仓库名称': item.store,
    '供应商名称': item.vendor,
    '商品名称': item.materialName,
    '商品编码': item.materialBarcode,
    '采购数量': item.quantity,
    '采购总金额': item.totalAmount,
    '操作人': item.operator,
    '操作日期': item.createTime
  }))

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(exportData)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '采购单列表')
  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  FileSaver.saveAs(blob, `采购单列表_${new Date().toLocaleDateString()}.xlsx`)
  ElMessage.success('导出成功')
}

const del=(row)=>{
  let deleteId = row.id
  let params = {
    id: deleteId,
  }
  purchaseDeleteService(params).then(() => {
    ElMessage.success("退货成功")
    getPurchase()
  })
}

</script>

<template>
  <el-form label-width="auto" class="form-style">
    <div class="form-group">
      <div class="form-item">
        <el-form-item label="单据号:">
          <el-input v-model="barcodeSearch" placeholder=""></el-input>
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="仓库:">
          <el-select v-model="storeSelect" placeholder="请选择仓库">
            <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="供应商:">
          <el-select v-model="vendorSelect" placeholder="请选择供应商">
            <el-option v-for="item in vendorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <el-button type="primary" @click="addDrawer = true">新增</el-button>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button @click="reset">重置</el-button>
      <el-button @click="refresh">刷新</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
  </el-form>

  <div class="table-wrapper">
    <el-table height="72vh" :data="tableData">
      <!--<el-table-column property="id" label="ID" />-->
      <el-table-column property="barcode" label="单据号" min-width="100vh" show-overflow-tooltip />
      <el-table-column property="store" label="仓库名称" show-overflow-tooltip />
      <el-table-column property="vendor" label="供应商名称" show-overflow-tooltip />
      <el-table-column property="materialName" label="商品名称" show-overflow-tooltip />
      <el-table-column property="materialBarcode" label="商品编码" show-overflow-tooltip />
      <el-table-column property="quantity" label="商品数量" show-overflow-tooltip />
      <el-table-column property="totalAmount" label="采购总金额" show-overflow-tooltip />
      <el-table-column property="operator" label="操作人" show-overflow-tooltip />
      <el-table-column property="createTime" label="创建日期" show-overflow-tooltip />
      <el-table-column label="退货操作" mshow-overflow-tooltip>
        <template #default="row">
          <el-popconfirm title="是否退回供应商?" @confirm='del(row.row)'>
            <template #reference>
              <el-button link type="primary">确认退货</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增表单 -->
    <el-drawer v-model="addDrawer" direction="rtl" :show-close="false" size="40%" title="新增采购订单">
      <el-form ref="formRef" :model="form" :rules="rules" style="width: 80%" label-width="auto">

        <el-form-item label="供应商:" prop="vendor">
          <el-select v-model="form.vendor" placeholder="请选择供应商">
            <el-option v-for="item in vendorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="存放仓库:" prop="store">
          <el-select v-model="form.store" placeholder="请选择存放仓库">
            <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称:" prop="material">
          <el-select v-model="form.material" placeholder="请选择商品名称">
            <el-option v-for="item in MaterialNameOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购数量:" prop="quantity">
          <el-input v-model="form.quantity" type="number" min="1" />
        </el-form-item>
        <el-button type="primary" @click="add">新增</el-button>
        <el-button @click="addCancel">取消</el-button>
      </el-form>
    </el-drawer>
  </div>

  <div class="example-pagination-block">
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" layout="prev, pager, next"
      :total="total" />
  </div>

</template>

<style scoped>
/* 表单 */
.form-style {
  margin-top: 5px;
}

/* 第1行盒子 */
.form-group {
  margin-left: 2vh;
}

/* 第1行盒子-表单组件 */
.form-item {
  display: inline-block;
  /* 行内显示 */
  margin-right: 3vh;
}

/* 第1行盒子-表单组件-输入框 */
.form-item .el-form-item {
  width: 40vh;
}

/* 第2行组件-按钮 */
.button-group .el-button {
  width: 12vh;
}

/* 第3行表格盒子 */
.table-wrapper {
  margin-left: 2vh;
}

/* 分页条盒子 */
.example-pagination-block {
  padding-left: 44%;
  margin-top: 10px;
  /* 根据需要调整上边距 */
}
</style>